<template>
	<view>
		<u-upload ref="upload" action="http://wlgc5.oss-cn-shanghai.aliyuncs.com" :max-size="5 * 1024 * 1024" max-count="1" :before-upload="beforeUpload"
			:custom-btn="true" :show-progress="false" :form-data="formDate" :multiple="false" :disabled="false"
			:show-upload-list="true" width="0" height="0" :limitType="limitType" @on-success="onSuccess" >

			<u-avatar slot="addBtn" :src="vuex_user.headImg" size="140"></u-avatar>

		</u-upload>
	</view>
</template>

<script>
	let _this = {}
	export default {
		name: "oss-upload",
		
		data() {
			return {
				//请求服务器的地址
				action: 'http://wlgc5.oss-cn-shanghai.aliyuncs.com',
				formDate: {},
				limitType: ['png', 'jpg', 'jpeg', 'webp'],
				upFileName: '',
				imgUrl:''
			};
		},
		created() {
			
			_this = this
		},
		methods: {
			/**
			 * 上传前的钩子
			 * 注意 在小程序中 this 可能会丢失  所以需要定义局部变量
			 * 然后再created（）中  声明变量  = this
			 * */
			async beforeUpload(index, list) {
				
				
				const {
					file
				} = list[0]
				console.log(file)
				// #ifdef H5
				const fileName = file.name
				// #endif
				//小程序获取方法  用path
				// #ifndef H5
				const fileName = file.path
				// #endif
				//请求api  获取oss token
				const ossToken = await _this.$u.api.authOssToken()
				
				//
				//设置上传域名
				// _this.action = ossToken.host
				//处理唯一文件名
				const suffix = fileName.slice(fileName.lastIndexOf('.'))
				const upFileName = _this.$u.guid(32) + suffix
				
				_this.upFileName = upFileName
				
				//额外上传参数
				_this.formDate = {
					'key': ossToken.dir+'/'+ upFileName,
					'policy': ossToken.policy,
					'OSSAccessKeyId': ossToken.accessKeyId,
					'success_action_status': '200', //让服务端返回200,不然，默认会返回204
					'signature': ossToken.signature,
					'dir':ossToken.dir,
					'host':ossToken.host
				}
				console.log(ossToken)
				_this.imgUrl = ossToken.host+'/' + ossToken.dir+'/'+_this.upFileName
				
				return true;

			},
			/**
			 * 上传成功之后 
			 * */
			 async onSuccess(){
				 //移除预览区域的图片
				 this.$refs.upload.remove(0)
				 // 请求API更新头像
				 
				 await this.$u.api.userAvatar({img: _this.imgUrl})
				 
				 //更新缓存的用户信息
				 this.$u.utils.updateUser()
				 
				 this.$u.toast('更新成功')
			 }
		}
	}
</script>

<style>

</style>
